/**
 * @author 甜圆
 * @version v1.0.1
 * @date 2025/8/31 13:21
 * @package PACKAGE_NAME
 * @copyright 甜圆
 */
import java.io.*;

public class Test {
    public static void main(String[] args) {
        Person person = new Person("张三", 25);
        String filename = "person.ser"; // 序列化后保存的文件

        // --- 序列化（打包并存到硬盘）---
        try (FileOutputStream fileOut = new FileOutputStream(filename);
             ObjectOutputStream out = new ObjectOutputStream(fileOut)) {

            out.writeObject(person); // 关键代码：将对象写入输出流
            System.out.println("对象已序列化并保存到 " + filename);

        } catch (IOException i) {
            i.printStackTrace();
        }

        // --- 反序列化（从硬盘读取并拆包）---
        Person loadedPerson = null;
        try (FileInputStream fileIn = new FileInputStream(filename);
             ObjectInputStream in = new ObjectInputStream(fileIn)) {

            loadedPerson = (Person) in.readObject(); // 关键代码：从输入流读取对象
            System.out.println("对象已从文件反序列化");

        } catch (IOException | ClassNotFoundException i) {
            i.printStackTrace();
            return;
        }

        // 比较一下原来的对象和“复活”的对象
        System.out.println("原始对象: " + person);
        System.out.println("反序列化后的对象: " + loadedPerson);
        System.out.println("它们是同一个吗？ " + (person == loadedPerson)); // false
        System.out.println("但它们的内容相等吗？ " + (person.toString().equals(loadedPerson.toString()))); // true
    }
}